require "event_editor/model"
require 'yaml'
module EventEditor
  class EventManager
    include DGO::TileMap
    def initialize(model)
      @model = model
    end

    def set_player_position(map_id, x, y)
      @model.set_player_position(map_id, x, y)
    end

    def render_event_box(s, x, y, w, h, offset_x, offset_y, gw, gh, selected, chip_data)
      x1 = x * gw
      x2 = x1 + w * gw - 1
      y2 = (y + 1) * gh
      y1 = y2 - h * gh + 1
      
      if selected
        s.render_rect(x1 + 2, y1 + 2, x2 - x1 - 2, y2 - y1 - 2, Color.new(255, 255, 55, 200))
        s.render_rect_border(x1 + 1, y1 + 1, x2, y2, Color.new(0, 0, 0, 255))
        s.render_rect_border(x1 + 2, y1 + 2, x2 - 1, y2 - 1, Color.new(255, 255, 55, 255))
      else
        s.render_rect(x1 + 2, y1 + 2, gw - 2, gh - 2, Color.new(255, 55, 255, 200))
        s.render_rect(x1 + 2, y1 + 2, x2 - x1 - 2, y2 - y1 - 2, Color.new(255, 255, 255, 100))
        s.render_rect_border(x1 + 1, y1 + 1, x2, y2, Color.new(0, 0, 0, 255))
        s.render_rect_border(x1 + 2, y1 + 2, x2 - 1, y2 - 1, Color.new(255, 255, 255, 255))
      end
      
      x1 = (x + offset_x) * gw
      y2 = (y + 1 + offset_y) * gh
      
      if chip_data[:chipset]
        chip_data[:chipset].render(s, x1, y2 - chip_data[:chipset].size_y, chip_data[:sx], chip_data[:sy], chip_data[:frame_no], chip_data[:dir], :alpha => 150)
      end
    end

    def render(s, gw, gh, rect)
      if @model.map_model.map_id == @model.player_map_id
        s.render_rect((@model.player_x - rect.left) * gw, (@model.player_y - rect.top) * gh, gw, gh, Color.new(120, 255, 120, 100))
      end
      @model.events.each do |event|
        next unless rect.include?(event['pos'][0], event['pos'][1])

        chipset = @model.get_chipset(event['pages'][0]['status']['chip_id'])
        dir = event['pages'][0]['status']['dir']
        frame_no = event['pages'][0]['status']['frame_no']
        selected = @model.selected_event == event
        
        t = event['pages'][0]['status']['hit_x']
        hit_x = t ? t : 1
        t = event['pages'][0]['status']['hit_y']
        hit_y = t ? t : 1
        t = event['pages'][0]['status']['off_x']
        offset_x = t ? t : 0
        t = event['pages'][0]['status']['off_y']
        offset_y = t ? t : 0
        
        self.render_event_box(s, event['pos'][0] - rect.left, event['pos'][1] - rect.top, hit_x, hit_y, offset_x, offset_y, $config.grid_width, $config.grid_height, selected,
        {:chipset => chipset, :sx => 0, :sy => 0, :frame_no => frame_no, :dir => dir}
        )
      end
    end
  end
end